package service

import (
	"context"
	"fmt"
	"net/http"
	"net/url"
	"time"

	"github.com/tencentyun/cos-go-sdk-v5"
)

var s3Client *cos.Client

const tak = "AKID53qPlurhXDh2CD7B49B5oNmzAKLD0jQy"
const tsk = "UmspaBhNDwZ3MUREwVs574saAaqvpbEi"

func COSInit() {
	u, _ := url.Parse("https://zq4-1318886512.cos.ap-shanghai.myqcloud.com")
	b := &cos.BaseURL{BucketURL: u}
	s3Client = cos.NewClient(b, &http.Client{})
}

func COSGetPresignedUploadURL(key string) (string, error) {
	ctx := context.Background()
	// 方法1 通过 PresignedURLOptions 设置 x-cos-security-token
	// PresignedURLOptions 提供用户添加请求参数和请求头部
	opt := &cos.PresignedURLOptions{
		Query:  &url.Values{},
		Header: &http.Header{},
	}
	opt.Query.Add("x-cos-security-token", "0987654311")
	// 获取预签名
	presignedURL, err := s3Client.Object.GetPresignedURL(ctx, http.MethodPut, key, tak, tsk, time.Hour, opt)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return "", err
	}
	var presignedURLString string = presignedURL.String()
	return presignedURLString, nil
}

func COSGetPresignedDownloadURL(key string) (string, error) {
	ctx := context.Background()
	// 方法1 通过 PresignedURLOptions 设置 x-cos-security-token
	// PresignedURLOptions 提供用户添加请求参数和请求头部
	opt := &cos.PresignedURLOptions{
		Query:  &url.Values{},
		Header: &http.Header{},
	}
	opt.Query.Add("x-cos-security-token", "<token>")
	// 获取预签名
	presignedURL, err := s3Client.Object.GetPresignedURL(ctx, http.MethodGet, key, tak, tsk, time.Hour, opt)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return "", err
	}
	// 通过预签名访问对象
	resp, err := http.Get(presignedURL.String())
	if err != nil {
		fmt.Printf("Error: %v\n", err)
	}
	defer resp.Body.Close()
	fmt.Println(presignedURL.String())
	fmt.Printf("resp:%v\n", resp)
	return presignedURL.String(), nil
}
